// pages/search/search.js
var api = require("../../utils/api");
var common = require("../../utils/public.js") //引入public.js脚本
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 购物车传参
    activityName: "",
    activityFullReduceId: "",
    //数量
    inputNum: '',
    //购物车原有数量
    inputNum1: '',
    cityNumber: {},//城市电话
    phoneNumber: {},//经理电话
    // 未登录时
    login: "",
    currentTab: 0,
    show: false,
    goodsList: [],
    ceshi: [],
    resval: "",
    inputShowed: true,
    getGoodsBrand: [],
    priceindex: null,
    nav: {
      all: "综合",
      price: "价格",
      choose: "筛选"
    },
    masking: 'masking',
    vals: [],
    num: 0,
    number: 0,
    index: 0,
    zindex: 0,
    zindex1: 0,
    vipFlag: 0
  },

  onLoad: function (options) {
    let that = this
    //搜索框结果
    this.setData({
      activityFullReduceId: options.activityFullReduceId,
      activityName: options.activityName,
      ticketId: options.ticketId,
      type: wx.getStorageSync('type')
    })
    api.phoneList({
      id: wx.getStorageSync("cityId")
    }).then(res => {
      if (res.result) {
        that.setData({
          cityNumber: res.body.cityInfo,
          phoneNumber: res.body.customerManager,
        })
      }
    })
  },

  onShow: function () {
    let that = this;
    //判断登录·
    that.setData({
      login: wx.getStorageSync('token') ? wx.getStorageSync('codeNum') == 99 ? true : false : false,
      loginCode: wx.getStorageSync('codeNum') == 103 ? true : wx.getStorageSync('codeNum') == 105 ? true : false,
      loginCode1: wx.getStorageSync('codeNum') == 104 ? true : false,
      vipFlag: Number(wx.getStorageSync('vipFlag')) 
    })
    // 调搜索公共接口
    that.activitySearch('default');
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  clickTab: function (e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      //不相等
      that.setData({
        currentTab: e.target.dataset.current
      })
      // 调用接口刷新页面
      if (e.target.dataset.current == 0) {
        this.setData({
          priceindex: null
        })
        that.activitySearch('default');
      } else if (e.target.dataset.current == 1) {
        this.setData({
          priceindex: 0
        })
        that.activitySearch('price_asc');
      }
    }
  },
  // 价格升序降序
  priceIndex(e) {
    let {
      priceindex
    } = e.currentTarget.dataset;
    this.setData({
      priceindex
    })
    if (priceindex == 0) {
      this.activitySearch("price_asc")
    } else {
      this.activitySearch("price_desc")
    }
  },
  //  品牌
  pinp(e) {
    let that = this;
    let { index } = e.currentTarget.dataset;
    let { getGoodsBrand, vals } = that.data;
    getGoodsBrand.forEach((v, i) => {
      if (index == i) {
        v.chos = !v.chos;
        that.setData({
          getGoodsBrand,
        })
        if (v.chos && vals.length < getGoodsBrand.length) {
          that.setData({
            vals: vals.concat(v.brandName),
          })
        } else if (!v.chos) {
          that.data.vals.forEach((items, ins) => {
            if (items == v.brandName) {
              vals.splice(ins, 1)
              that.setData({
                vals
              })
            }
          });
        }
      }
    })
  },
  // 搜索按钮
  searchBtn:common.debounceFunc(function(e){
    let resval = e.detail.value;
    //为空和输入空格
    if (resval.replace(/(^\s*)|(\s*$)/g, "") == "") {
    } else {
      // 调用公共
      this.activitySearch('default');
    }
  },1000), 
  //  公共接口(排序)
  activitySearch(sort) {
    let that = this;
    let { resval, activityFullReduceId } = that.data;
    // 调用接口 name:标题名称,brandName:品牌名称 activityFullReduceId购物车传过来的
    api.activitySearch({
      activityFullReduceId: activityFullReduceId || '',
      // brandName: '',
      name: resval,
      serchFlag: sort,
      page: {},
      userId: wx.getStorageSync("openId"),
      cityId: wx.getStorageSync("cityId")
    }).then(res => {
      if (res.result) {
        let goods = res.body.getActiveGoods;
        for (var i = 0; i < goods.length; i++) { //遍历数组 给数组元素加上隐藏
          let goodsDetailsEntityList = goods[i].goodsDetailsEntityList
          goods[i].choice = true;
          goodsDetailsEntityList.forEach(v => {
            if (v.amount > 0) {
              goods[i].choice = false;
            }
          })
        }
        that.setData({
          goodsList: goods,
          masking: '',
        })
      }
    })
  },
  //品牌筛选接口
  showPopup() {
    let that = this;
    let {
      resval,
      ticketId
    } = that.data;
    that.setData({
      show: true
    });
    // brandNmae: 品牌名, goodsName: 搜索名,
    api.getGoodsBrand({
      ticketId: ticketId,
      brandName: '',
      goodsName: resval,
      serchFlag: 'default'
    }).then(res => {
      if (res.result) {
        that.setData({
          getGoodsBrand: res.object
        })
      }
    })
  },
  // 重置
  handleReset() {
    let getGoodsBrand = this.data.getGoodsBrand;
    getGoodsBrand.forEach((v, i) => { v.chos = null; })
    this.setData({
      vals: [],
      getGoodsBrand
    })
  },
  //确认
  handleAffirm() {
    let that = this;
    let resval = that.data.resval;
    let vals = that.data.vals;
    let str = '';
    for (let i = 0; i < vals.length; i++) {
      str += "'" + vals[i] + "',"
    }
    let stringVals = str.substring(0, str.length - 1)
    if (stringVals != "") {
      // brandNmae: 品牌名, goodsName: 搜索名,
      api.searchIndex({
        brandName: stringVals,
        name: resval,
        searchFlag: 'default',
        page: {},
        userId: wx.getStorageSync("openId"),
        cityId: wx.getStorageSync("cityId")
      })
        .then(res => {
          if (res.result) {
            if(wx.getStorageSync('type') == "2"){
              res.object.records.forEach(v=>{
                v.goodsDetailsEntityList.forEach(j=>{
                  api.roleSwitch(j)
                })
              })
            }
            let goods = res.object.records;
            for (var i = 0; i < goods.length; i++) { //遍历数组 给数组元素加上隐藏
              goods[i].choice = true;
            }
            that.setData({
              goodsList: goods,
              show: false,
              vals: []
            })
          }
        })
    } else {
      that.setData({
        show: false
      })
    }
  },
  // -----------------------搜索栏-------------------------
  inputTyping: function (e) {
    this.setData({
      resval: e.detail.value
    });
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  clearInput: function () {
    this.setData({
      resval: ""
    });
    wx.hideKeyboard({
      complete: res => {
        this.setData({
          resval: ""
        });
      }
    })
  },
  //---------------- 商品方面信息-------------------------
  //选规格
  more(e) {
    let that = this
    // 获取选中的index索引
    var index = e.currentTarget.dataset.index;
    // 获取到商品列表数据
    var goodsList = that.data.goodsList;
    // 循环数组数据，判断----规格 --收起
    goodsList[index].choice = !goodsList[index].choice;
    //重新渲染数据
    that.setData({
      goodsList: goodsList
    })

  },
  //增加数量
  addCount: function (e) {
    let that = this
    let { index1, index } = e.currentTarget.dataset;
    let goodsList = that.data.goodsList;
    let goLists = goodsList[index].goodsDetailsEntityList[index1];
    let startNum = goodsList[index].goodsDetailsEntityList[index1].startNum
    let amount = goLists.amount;
    if (amount < startNum) {
      amount = Number(startNum); 
    } else {
      amount = Number(amount + 1);
    }
    that.nums(amount, index, goodsList, goLists);
  },
  //减少数量(+ -)
  btnMinus(e) {
    let that = this
    let { index1, index } = e.currentTarget.dataset;
    let goodsList = that.data.goodsList;
    let goLists = goodsList[index].goodsDetailsEntityList[index1];
    let startNum = goodsList[index].goodsDetailsEntityList[index1].startNum
    let amount = goLists.amount;
    if (amount == startNum) {
      amount = 0;
    } else {
      amount = amount - 1;
    }

    that.nums(amount, index, goodsList, goLists);

  },
  //调用商品接口(公共接口)
  nums(number, index, goodsList, goLists) {
    let that = this
    let amount = number;
    let userInfoId = wx.getStorageSync('openId');
    let cityId = wx.getStorageSync('cityId')
    let goodsName = goodsList[index].name;
    let goodsDetailsId = goLists.id;
    let price = goLists.price;
    let totalPrice = goLists.priceVip;
    // 价格
    if (goLists.activitySeckillId == null) {
      if (wx.getStorageSync("vipFlag") == 1) {
        price = goLists.salesPriceVip
        totalPrice = price * amount
      } else {
        price = goLists.salesPrice
        totalPrice = price * amount
      }
    } else {
      price = goLists.seckillPrice
      totalPrice = price * amount
    }
    api.set_amount({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        goLists.amount = amount;
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        } else {
          wx.hideTabBarRedDot({
            index: 3
          })
        }
        that.setData({
          goodsList: goodsList
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })

  },
  next: function (e) {
    if (wx.getStorageSync('codeNum') == 103) {
      //未注册商铺 跳转商铺注册页
      wx.showToast({
        title: '您还未注册店铺！',
        icon: 'none',
        duration: 1500
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/sf_xz/sf_xz?type=' + 1,
        })

      }, 1000)
    } else if (wx.getStorageSync('codeNum') == 104) {
      //商铺审核中 
      wx.showToast({
        title: '您的商铺审核中！',
        icon: 'none',
        duration: 1000
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/shopBack/shopBack?type=' + 1,
        })

      }, 1000)

    }
    else if (wx.getStorageSync('codeNum') == 105) {
      //商铺审核未通过
      wx.showToast({
        title: '您申请的店铺暂未审核通过！',
        icon: 'none',
        duration: 1000
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/sf_xz/sf_xz?type=' + 1,
        })

      }, 1000)
    }
    else if (wx.getStorageSync('codeNum') == 99) {
      let { shopid, id } = e.currentTarget.dataset;
      // 详情
      wx.navigateTo({
        url: '/pages/detail/detail?id=' + id + '&shopid=' + shopid,
      })
    } else if (wx.getStorageSync("userMessage") == '') {
      wx.navigateTo({
        url: '/pages/userMess/userMess',
      })

    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  //获取数量
  inputNum(e) {
    let that = this
    if (e.detail.value == "" || e.detail.value == 0 || e.detail.value < that.data.detailStartNum) {
      that.setData({
        inputNum: Number(that.data.inputNum1)
      })
    } else {
      that.setData({
        inputNum: Number(e.detail.value)
      })
    }
  },
  bindconfocus(e) {
    let index1 = e.currentTarget.dataset.index1;
    let goLists = e.currentTarget.dataset.item.goodsDetailsEntityList[index1]
    this.setData({
      inputNum1: e.currentTarget.dataset.item.goodsDetailsEntityList[index1].amount,
      detailStartNum: goLists.startNum
    })
  },
  //失去焦点
  bindconfirm(e) {
    let that = this;
    let index1 = e.currentTarget.dataset.index1
    let index = e.currentTarget.dataset.index
    let goodsList = that.data.goodsList
    let goLists = e.currentTarget.dataset.item.goodsDetailsEntityList[index1]
    if (that.data.inputNum != "") {
      if (that.data.inputNum >= that.data.detailStartNum) {
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = e.currentTarget.dataset.item.name
        let goodsDetailsId = goLists.id
        let price = goLists.price
        let amount = Number(that.data.inputNum)
        let totalPrice = goLists.priceVip
        if (goLists.activitySeckillId == null) {
          if (wx.getStorageSync("vipFlag") == 1) {
            price = goLists.salesPriceVip
            totalPrice = price * amount
          } else {
            price = goLists.salesPrice
            totalPrice = price * amount
          }
        } else {
          price = goLists.seckillPrice
          totalPrice = price * amount
        }
        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {
          if (res.result) {
            goodsList[index].goodsDetailsEntityList[index1].amount = that.data.inputNum;
            that.setData({
              goodsList
            });
            if (res.data > 0) {
              wx.setTabBarBadge({
                index: 3,
                text: res.data //显示的内容 
              })
            } else {
              wx.hideTabBarRedDot({
                index: 3
              })
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            goodsList[index].goodsDetailsEntityList[index1].amount = that.data.inputNum1;
            that.setData({
              goodsList
            });
          }

        })
      } else {
        if (that.data.inputNum != "") {
          wx.showToast({
            title: '请输入最小起送数量' + that.data.detailStartNum,
            icon: 'none'
          })
          // goodsList[index].goodsDetailsEntityList[index1].amount = that.data.inputNum1;
          // that.setData({
          //   goodsList,
          //   inputNum: Number(that.data.inputNum1)
          // });
        }
      }
    }
  },
  // 首页打电话
  callGetPhone: function () {
    wx.navigateTo({
      url: '/pages/kefu/kefu',
    })
  },
})